<script setup>
import { ref } from 'vue'

import { onMounted } from 'vue'

//学生加入的课程
const categorys = ref([
  {
    id: 3,
    categoryName: '大数据',
    categoryAlias: '后端',
    createTime: '2023-09-02 12:06:59',
    updateTime: '2023-09-02 12:06:59'
  }
])
//声明一个异步的函数
import {
  subjectCategoryListService,
  subjectCategoryAddService,
  subjectCategoryUpdateService,
  subjectCategoryDeleteService
} from '@/api/subject.js'

const subjectCategoryList = async () => {
  let result = await subjectCategoryListService();
  categorys.value = result.data
}
subjectCategoryList()
//控制添加分类弹窗
const dialogVisible = ref(false)

//添加分类数据模型
const categoryModel = ref({
  categoryName: '',
  categoryAlias: '',
  taskId: '',
  createUser: ''
})
//添加分类表单校验
const rules = {
  categoryName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  categoryAlias: [
    { required: true, message: '请输入课程别名', trigger: 'blur' }
  ]
}

//添加分类
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllTasks, getTaskById } from '@/api/task.js'
import throttle from 'lodash/throttle'
import useUserInfoStore from '@/stores/userInfo.js'

const addCategory = throttle(async () => {
  if (categoryModel.value.taskId === '') {
    ElMessage.error('请选择课程名称')
    return
  }
  categoryModel.value.createUser = useUserInfoStore().info.id
  let result = await subjectCategoryAddService(categoryModel.value)
  ElMessage.success(result.msg ? result.msg : '添加成功')
  categoryModel.value.taskId = ''
  //调用获取所有课程函数
  await subjectCategoryList()
  dialogVisible.value = false
}, 3000)

const title = ref('')


const updateCategory = async () => {
  let result = await subjectCategoryUpdateService(categoryModel.value)
  ElMessage.success(result.msg ? result.msg : '修改成功')
  //调用获取所有课程函数
  await subjectCategoryList()
  //隐藏弹窗
  dialogVisible.value = false
}

//清空模型的数据
const clearData = throttle(() => {
  categoryModel.value.categoryName = ''
  categoryModel.value.categoryAlias = ''
}, 1000)

// 所有任务选项
let tasksOptions = ref([])

let allTasks = ref([])

// 获取到所有的任务
const getAllTasksList = async () => {
  try {
    let result = await getAllTasks()
    if (result.code === 0) {
      allTasks.value = result.data
      tasksOptions.value = result.data.map(item => {
        return {
          label: item.taskName,
          value: item.taskId
        }
      })
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}
onMounted(() => {
  getAllTasksList()
})

const changeTaskHandler = async e => {
  try {
    let task = await getTaskById(e)
    if (task.code === 0) {
      categoryModel.value.categoryName = task.data.taskName
      categoryModel.value.categoryAlias = task.data.taskDescription
      categoryModel.value.taskId = e
    } else {
      ElMessage.error(task.message)
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

//退出课程
const deleteCategory = throttle(row => {
  ElMessageBox.confirm('你确定要退出这个课程吗？', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await subjectCategoryDeleteService(row.id)
      ElMessage({
        type: 'success',
        message: '已退出课程!'
      })
      //调用获取所有课程函数
      await subjectCategoryList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消退出'
      })
    })
}, 1000)
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>课程分类</span>
        <div class="extra">
          <el-button
            type="primary"
            @click="
              dialogVisible = true,
              title = '选学课程',
              clearData()
            "
            >选学课程</el-button
          >
        </div>
      </div>
    </template>
    <el-table :data="categorys" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"></el-table-column>
      <el-table-column label="课程名称" prop="categoryName"></el-table-column>
      <el-table-column label="描述" prop="categoryAlias"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            link
            type="danger"
            icon="Delete"
            size="small"
            @click="deleteCategory(row)"
            >退出课程</el-button
          >
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="categoryModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="课程名称" prop="taskId">
          <el-select
            v-model="categoryModel.taskId"
            @change="changeTaskHandler"
            placeholder="请选择课程名称"
          >
            <el-option
              v-for="item in tasksOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="title === '选学课程' ? addCategory() : updateCategory()"
            >确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
